package com.wisdytech.linkdcs.tool.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.ImportExcelUtils;
import com.wisdytech.common.utils.PojoConvertUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.dao.ToolCheckItemBakDao;
import com.wisdytech.linkdcs.tool.dao.ToolCheckItemDao;
import com.wisdytech.linkdcs.tool.dao.TtEqToolDao;
import com.wisdytech.linkdcs.tool.model.ToolCheckItem;
import com.wisdytech.linkdcs.tool.model.ToolCheckItemBak;
import com.wisdytech.linkdcs.tool.model.ToolMaintainItem;
import com.wisdytech.linkdcs.tool.model.TtEqTool;
import com.wisdytech.linkdcs.tool.service.IToolCheckItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-12
 */
@Service
@Transactional
public class ToolCheckItemServiceImpl extends BaseService<ToolCheckItemDao, ToolCheckItem> implements IToolCheckItemService {

    @Resource
    private ToolCheckItemDao toolCheckItemDao;

    @Resource
    private TtEqToolDao ttEqToolDao;
	
	@Resource
    private ToolCheckItemBakDao toolCheckItemBakDao;

    @Override
    public PageInfo<ToolCheckItem> getToolCheckItemByFilter(String toolCode, Filter filter) {
        if (StringUtils.isBlank(toolCode)) {
            return new PageInfo<>(new ArrayList<>());
        }
        EntityWrapper<ToolCheckItem> ew = new EntityWrapper<>();
        ew.eq("del_flag", CommonConstants.DEL_FLAG)
                .eq("tool_code", toolCode);
        List<ToolCheckItem> list = this.beforeList(ToolCheckItemDao.class, filter).selectList(ew);
        return new PageInfo<>(list);
    }

    @Override
    public Boolean saveOrUpdateCheckItem(ToolCheckItem toolCheckItem, SysUser operator) {
        Integer operateCount = 0;
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        if (toolCheckItem == null || StringUtils.isBlank(toolCheckItem.getCheckProject()) || StringUtils.isBlank(toolCheckItem.getToolCode()))
            throw new ServiceException("参数错误");

        EntityWrapper<ToolCheckItem> ew = new EntityWrapper<>();
        ew.eq("tool_code", toolCheckItem.getToolCode())
                .eq("check_project", toolCheckItem.getCheckProject())
                .eq("del_flag", CommonConstants.DEL_FLAG);
        if (StringUtils.isNotBlank(toolCheckItem.getPkId())) {
            ew.ne("pk_id", toolCheckItem.getPkId());
        }
        Integer count = toolCheckItemDao.selectCount(ew);
        if (count > 0) {
            throw new ServiceException("校验项目重复");
        }
		String pkId = BaseUtil.getUUID();

        String snapshotId = BaseUtil.getUUID();
        //修改
        if (StringUtils.isNotBlank(toolCheckItem.getPkId())) {
            pkId = toolCheckItem.getPkId();
            toolCheckItem.setUpdateDate(new Date());
            toolCheckItem.setUpdateUser(operator.getUsername());
            toolCheckItem.setVersion(snapshotId);
            operateCount = toolCheckItemDao.updateById(toolCheckItem);
        } else {
            //新增
            toolCheckItem.setPkId(pkId);
            toolCheckItem.setCreateDate(new Date());
            toolCheckItem.setCreateUser(operator.getUsername());
            toolCheckItem.setDelFlag(CommonConstants.DEL_FLAG);
            toolCheckItem.setVersion(snapshotId);
            operateCount = toolCheckItemDao.insert(toolCheckItem);
        }

        // 查询快照
        ToolCheckItem snapshot = toolCheckItemDao.selectById(pkId);
        // 复制快照
        ToolCheckItemBak toolCheckItemBak = PojoConvertUtil.convertPojo(snapshot,ToolCheckItemBak.class);
        toolCheckItemBak.setPkId(snapshotId);
        toolCheckItemBak.setDelFlag(CommonConstants.DEL_FLAG);
        // 保存快照
        toolCheckItemBakDao.insert(toolCheckItemBak);


        return operateCount > 0;
    }

    @Override
    public Boolean deleteToolCheckItem(String pkIds, SysUser operator) {
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        String[] deletePkIds = pkIds.split(",");
        if (deletePkIds.length == 0)
            return true;
        List<String> pkIdCollection = Arrays.asList(deletePkIds);
        Integer deleteCount = toolCheckItemDao.deleteBatchIds(pkIdCollection);
        return deleteCount > 0;
    }

    @Override
    public ToolCheckItem getToolCheckItemById(String pkId) {
        if (StringUtils.isBlank(pkId)) {
            return null;
        }
        return toolCheckItemDao.selectById(pkId);
    }

    @Override
    public void batchImportToolCheckItem(MultipartFile file, SysUser operator) {
        if (file == null) {
            throw new ServiceException("文件为空");
        }
        if (operator ==null) {
            throw new ServiceException("操作人不能为空");
        }
        int errorRow=0;
        try {
            String fileName = file.getOriginalFilename();
            InputStream in = file.getInputStream();
            List<List<Object>> data = ImportExcelUtils.getDataListByExcel(in, fileName);
            if (data == null || data.size() == 0) {
                throw new ServiceException("表格数据为空");
            }
            List<ToolMaintainItem> list = new ArrayList<>();

            //i 从1开始，去除表头数据，根据自己的模板而定
            for (int i = 1; i < data.size(); i++) {
                ToolCheckItem item = new ToolCheckItem();
                item.setCreateDate(new Date());
                item.setCreateUser(operator.getUsername());
                item.setDelFlag(CommonConstants.DEL_FLAG);
                errorRow = i;
                item.setPkId(BaseUtil.getUUID());
                if (data.get(i).get(0) == null||StringUtils.isBlank(data.get(i).get(0).toString())) {
                    throw new ServiceException("第"+i+"行第1列工装编码数据不能为空");
                }
                if(!checkToolCode(data.get(i).get(0).toString())) {
                    throw new ServiceException("第"+i+"行第1列工装编码数据在工装库中不存在");
                }
                item.setToolCode(data.get(i).get(0).toString());

                if (data.get(i).get(1) == null||StringUtils.isBlank(data.get(i).get(1).toString())) {
                    throw new ServiceException("第"+i+"行第2列工装校验项目数据不能为空");
                }
                if (!checkCheckProject(item.getToolCode(),data.get(i).get(1).toString())) {
                    throw new ServiceException("第"+i+"行第2列工装校验项目数据重复");
                }
                item.setCheckProject(data.get(i).get(1).toString());
                if(data.get(i).size()>2) {
                    if((!"1".equals(data.get(i).get(2).toString()))&&(!"2".equals(data.get(i).get(2).toString()))) {
                        throw new ServiceException("第"+i+"行第3列工装校验项属性数据无效");
                    }
                    item.setCheckAttr(data.get(i).get(2).toString());
                }
                if(data.get(i).size()>3) {
                    item.setCheckTool(data.get(i).get(3).toString());
                }
                if(data.get(i).size()>4) {
                    item.setPrecision(data.get(i).get(4).toString());
                }
                if(data.get(i).size()>5) {
                    item.setStandardCheckVal(data.get(i).get(5).toString());
                }
                if(data.get(i).size()>6) {
                    item.setMaxCheckVal(data.get(i).get(6).toString());
                }
                if(data.get(i).size()>7) {
                    item.setMinCheckVal(data.get(i).get(7).toString());
                }
                if(data.get(i).size()>8) {
                    item.setCheckMethod(data.get(i).get(8).toString());
                }

                //TODO 批量插入
                toolCheckItemDao.insert(item);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件出错");
        } catch (IndexOutOfBoundsException e2) {
            e2.printStackTrace();
            throw new ServiceException("表格中第"+errorRow+"存在空数据");
        }
    }

    private Boolean checkToolCode(String toolCode) {
        if (StringUtils.isBlank(toolCode)) {
            return false;
        }
        EntityWrapper<TtEqTool> ew = new EntityWrapper<>();
        ew.eq("tool_code",toolCode).eq("del_flag",CommonConstants.DEL_FLAG);
        return ttEqToolDao.selectCount(ew)>0;

    }

    private Boolean checkCheckProject(String toolCode,String checkProject) {
        if (StringUtils.isBlank(checkProject)) {
            return false;
        }
        EntityWrapper<ToolCheckItem> ew = new EntityWrapper<>();
        ew.eq("check_project",checkProject).eq("tool_code",toolCode).eq("del_flag",CommonConstants.DEL_FLAG);
        return toolCheckItemDao.selectCount(ew)==0;

    }
}
